package com.titleevaluation.service;

import com.titleevaluation.entity.Application;
import com.titleevaluation.entity.WorkAchievements;
import com.titleevaluation.repository.ApplicationRepository;
import com.titleevaluation.repository.WorkAchievementsRepository;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
public class WorkAchievementsService {

    private final WorkAchievementsRepository workAchievementsRepository;
    private final ApplicationRepository applicationRepository;

    public WorkAchievementsService(WorkAchievementsRepository workAchievementsRepository, ApplicationRepository applicationRepository) {
        this.workAchievementsRepository = workAchievementsRepository;
        this.applicationRepository = applicationRepository;
    }

    public WorkAchievements createWorkAchievements(Long applicationId, WorkAchievements workAchievements) {
        Application application = applicationRepository.findById(applicationId)
                .orElseThrow(() -> new RuntimeException("Application not found"));
        workAchievements.setApplication(application);
        workAchievements.setCreatedAt(LocalDateTime.now());
        workAchievements.setUpdatedAt(LocalDateTime.now());
        return workAchievementsRepository.save(workAchievements);
    }

    public List<WorkAchievements> getWorkAchievementsByApplicationId(Long applicationId) {
        return workAchievementsRepository.findByApplicationId(applicationId);
    }

    public Optional<WorkAchievements> getWorkAchievementsById(Long id) {
        return workAchievementsRepository.findById(id);
    }

    public WorkAchievements updateWorkAchievements(Long id, WorkAchievements updatedWorkAchievements) {
        WorkAchievements existingWorkAchievements = workAchievementsRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("WorkAchievements not found"));

        existingWorkAchievements.setSequenceNo(updatedWorkAchievements.getSequenceNo());
        existingWorkAchievements.setProjectName(updatedWorkAchievements.getProjectName());
        existingWorkAchievements.setPersonalRole(updatedWorkAchievements.getPersonalRole());
        existingWorkAchievements.setStartDate(updatedWorkAchievements.getStartDate());
        existingWorkAchievements.setEndDate(updatedWorkAchievements.getEndDate());
        existingWorkAchievements.setOperation(updatedWorkAchievements.getOperation());
        existingWorkAchievements.setUpdatedAt(LocalDateTime.now());

        return workAchievementsRepository.save(existingWorkAchievements);
    }

    public void deleteWorkAchievements(Long id) {
        workAchievementsRepository.deleteById(id);
    }
}

